package daily

import daily.commons.Month

/**

 * User: zjzhai
 * Date: 10/10/13
 * Time: 8:48 PM

 */
class DateUtils {

    /**
     *
     * @param javascriptDate ex. Thu Oct 10 2013 21:08:35 GMT+0800 (CST)
     * @return
     */
    static Date JavascriptDateToJavaDate(String javascriptDate) {
        if (null == javascriptDate) {
            throw new RuntimeException('javascriptDate不能为空')
        }
        def dateArray = javascriptDate.split(' ')
        def HHmmss = dateArray[4].split(':')
        return new Date(year: Integer.parseInt(dateArray[3]) - 1900,
                month: Month.numberofShortName(dateArray[1]),
                date: Integer.parseInt(dateArray[2]),
                hours: Integer.parseInt(HHmmss[0]),
                minutes: Integer.parseInt(HHmmss[1]),
                seconds: Integer.parseInt(HHmmss[2])
        );
    }


    static Date startOfWeek(Date date){
        Calendar calendar = toCalendar(date)
        int min = calendar.getActualMinimum(Calendar.DAY_OF_WEEK);
        calendar.add(Calendar.DAY_OF_WEEK,min - calendar.get(Calendar.DAY_OF_WEEK))
        calendar.getTime();
    }

    static Date endOfWeek(Date date){
        Calendar calendar = toCalendar(date)
        int min = calendar.getActualMinimum(Calendar.DAY_OF_WEEK);
        calendar.add(Calendar.DAY_OF_WEEK,min - calendar.get(Calendar.DAY_OF_WEEK))
        calendar.add(Calendar.DAY_OF_WEEK,6);
        calendar.getTime();
    }


    static Date startOfMonth(Date date){
        Calendar calendar = toCalendar(date)

        calendar.set(Calendar.DAY_OF_MONTH,1)
        calendar.getTime()
    }

    static Date endOfMonth(Date date){

        Calendar calendar = toCalendar(date)
        calendar.set(Calendar.DAY_OF_MONTH,-1)
        calendar.getTime()
    }

    static Date startOfDay(Date date){
        Calendar calendar =toCalendar(date)
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.getTime()
    }

    static Date endOfDay(Date date){
        Calendar calendar = toCalendar(date)
        calendar.set(Calendar.HOUR, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        calendar.getTime()
    }

    static Calendar toCalendar(Date date){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }



}
